package com.suncky.frame.utils.activityresult;

import android.app.Activity;
import android.content.Intent;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

/**
 * author： gl
 * time： 2021/4/9 14:40
 * description：activity result工具类
 */
public class ActivityResultHelper {
    private static final String TAG = "ActivityResultHelper";
    private ActivityResultFragment activityResultFragment;

    public ActivityResultHelper(FragmentActivity activity) {
        initFragment(activity);
    }

    public ActivityResultHelper(Fragment fragment) {
        this(fragment.getActivity());
    }

    private void initFragment(FragmentActivity activity) {
        activityResultFragment =  (ActivityResultFragment)activity.getSupportFragmentManager().findFragmentByTag(TAG);
        if (activityResultFragment == null) {
            activityResultFragment = new ActivityResultFragment();
            FragmentManager fragmentManager = activity.getSupportFragmentManager();
            fragmentManager.beginTransaction().add(activityResultFragment, TAG).commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
    }

    public void startForResult(Intent intent, int requestCode, ActivityResultCallback callback) {
        activityResultFragment.startForResult(intent, requestCode, callback);
    }

    public void startForResult(Class<Activity> cls, int requestCode, ActivityResultCallback callback) {
        activityResultFragment.startForResult(new Intent(activityResultFragment.getActivity(), cls), requestCode, callback);
    }

    public interface ActivityResultCallback {
        void onActivityResult(int requestCode, int resultCode, Intent data);
    }
}
